package com.ufo.store.management.ui.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.adapter.Isszmbalv3StockRecyclerViewAdapter;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.Isszmbalv3StockInfo;
import com.ufo.store.management.entity.SerializableList;
import com.ufo.store.management.entity.SerializableMap;
import com.ufo.store.management.ui.activity.Isszmbalv3StockEditActivity;
import com.ufo.store.management.ui.activity.Isszmbalv3StockSalesActivity;
import com.ufo.store.management.utils.DialogUtil;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.PtrClassicFrameLayout.LoadingFooter;
import com.ufo.store.management.widget.PtrClassicFrameLayout.LoadingHeader;
import com.ufo.store.management.widget.recyclerview.EndlessRecyclerOnScrollListener;

import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

import static android.app.Activity.RESULT_OK;

/**
 *  作者：taoli on 2017/2/27 0027 13:45
 *  
 */
public class Isszmbalv3StockListFragment extends BaseLazyFragment implements Handler.Callback {
    public static final String TAG = Isszmbalv3StockListFragment.class.getSimpleName();
    private final int ACTIVITY_RESULT_STOCK_DETAIL = 100;

    private final int LOAD_DATA_FINISH = 1;
    private final int REFRESH_DATA_FINISH = 2;

    private int mPosition = -1;

    private Handler mHandler = null;

    private ImageView get_stock_list_fail_iv = null;
    private TextView get_stock_list_fail_tv = null;

    private RecyclerView mIsszmbalv3StockRecyclerView = null;
    private Isszmbalv3StockRecyclerViewAdapter mIsszmbalv3StockRecyclerViewAdapter = null;
    private PtrClassicFrameLayout mPtrFrame;

    private int mStartIndex = -1;
    private int mMaxStockIndex = -1;
    private int mMaxStockCountByTypeId = -1;

    private Object mLock = new Object();
    private boolean bCanRefresh = true;

    private SerializableMap mIsszmbalv3StockTypeMap;
    private SerializableList mIsszmbalv3SupcustInfoSerializableList;

    private String mStockTypeId = "-1";

    private int ListStyle;

    private boolean mIsTitleLlHided = false;
    private boolean mCanLoadMore = true;

    private int SortMode = -1;     // 0:名字升序   1：名字降序    2：ID升序  3：ID降序    4：价格升序     5：价格降序
    private int forbidExhibitPos = -1;   //在item被detail页查看期间禁止应用动画翻转

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case REFRESH_DATA_FINISH:
                if (mIsszmbalv3StockRecyclerViewAdapter != null) {
                    final List<Isszmbalv3StockInfo> data = (List<Isszmbalv3StockInfo>) msg.obj;
                    mPtrFrame.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mPtrFrame.refreshComplete();
                            mIsszmbalv3StockRecyclerViewAdapter.setData(data);
                            mIsszmbalv3StockRecyclerViewAdapter.notifyDataSetChanged();
                        }
                    }, 0);
                }
                break;
            case LOAD_DATA_FINISH:
                if (mIsszmbalv3StockRecyclerViewAdapter != null) {
                    final List<Isszmbalv3StockInfo> data = (List<Isszmbalv3StockInfo>) msg.obj;
                    mPtrFrame.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mPtrFrame.refreshComplete();
                            mIsszmbalv3StockRecyclerViewAdapter.insertData(data);
                            mIsszmbalv3StockRecyclerViewAdapter.notifyItemRangeInserted(mStartIndex - data.size(), data.size());
                        }
                    }, 0);
                }
                break;
            default:
                break;
        }
        return false;
    }

    /**
     * 布局文件ID
     *
     * @return
     */
    protected int getLayoutId() {
        return R.layout.fragment_isszmbalv3_stock_list;
    }


    /**
     * 初始化数据
     */
    protected void initData() {
        loaded();
        mHandler = new Handler(this);
        if (mIsszmbalv3StockTypeMap != null && mIsszmbalv3StockTypeMap.getMap() != null) {
            Map<String, String> map = mIsszmbalv3StockTypeMap.getMap();
            int i = 0;
            for (String key : map.keySet()) {
                if (i == mPosition) {
                    mStockTypeId = key;
                    break;
                }
                i++;
            }
        }
    }

    protected void onFirstUserVisible() {
        getIsszmbalv3StockInfoList(true);
    }

    protected void onUserVisible() {
    }

    protected void onFirstUserInvisible() {

    }

    protected void onUserInvisible() {

    }

    /**
     * 初始化组件
     */
    protected void initViewData(View entryView) {
        get_stock_list_fail_iv = (ImageView) entryView.findViewById(R.id.get_stock_list_fail_iv);
        get_stock_list_fail_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIsszmbalv3StockInfoList(true);
            }
        });
        get_stock_list_fail_tv = (TextView) entryView.findViewById(R.id.get_stock_list_fail_tv);

        mPtrFrame = (PtrClassicFrameLayout) entryView.findViewById(R.id.ptr);
        mPtrFrame.setLastUpdateTimeRelateObject(this);
        mPtrFrame.disableWhenHorizontalMove(true);
        mPtrFrame.setPtrHandler(ptrDefaultHandler2);//设置下拉上拉监听

        //设置头尾刷新布局（以下四步骤部必须按照顺序设置，否则无效）
        LoadingFooter ptrLoadUIHandler = new LoadingFooter(getContext());
        mPtrFrame.setFooterView(ptrLoadUIHandler);
        mPtrFrame.addPtrUIHandler(ptrLoadUIHandler);
        //添加头部处理功能
        LoadingHeader ptrRefreshUIHandler = new LoadingHeader(getContext());
        mPtrFrame.addPtrUIHandler(ptrRefreshUIHandler);
        mPtrFrame.setHeaderView(ptrRefreshUIHandler);

        mIsszmbalv3StockRecyclerView = (RecyclerView) entryView.findViewById(R.id.stock_recyclerview);
        if (ListStyle == 1) {
            mIsszmbalv3StockRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        } else if (ListStyle == 2) {
            mIsszmbalv3StockRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        }
        mIsszmbalv3StockRecyclerViewAdapter = new Isszmbalv3StockRecyclerViewAdapter(getActivity(), ListStyle, mIsszmbalv3StockTypeMap.getMap());
        mIsszmbalv3StockRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mIsszmbalv3StockRecyclerView.setHasFixedSize(true);
        mIsszmbalv3StockRecyclerView.setAdapter(mIsszmbalv3StockRecyclerViewAdapter);
        mIsszmbalv3StockRecyclerViewAdapter.setOnClickListener(new Isszmbalv3StockRecyclerViewAdapter.OnClickListener() {
            @Override
            public void onDetailClick(int position) {
                Isszmbalv3StockInfo isszmbalv3StockInfo = mIsszmbalv3StockRecyclerViewAdapter.getItem(position);
                Intent toIntent = new Intent(getActivity(), Isszmbalv3StockSalesActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("StockNo", isszmbalv3StockInfo.item_no);
                bundle.putString("StockName", isszmbalv3StockInfo.item_name);
                toIntent.putExtras(bundle);
                startActivity(toIntent);
                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(-1);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }

            @Override
            public void onDeleteClick(int position) {
                showDeleteItemDialog(position);
                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(-1);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }

            @Override
            public void onItemClick(View v, int position) {
                Isszmbalv3StockInfo isszmbalv3StockInfo = mIsszmbalv3StockRecyclerViewAdapter.getItem(position);
                Intent toIntent = new Intent(getActivity(), Isszmbalv3StockEditActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("Isszmbalv3StockInfo", isszmbalv3StockInfo);
                bundle.putSerializable("Isszmbalv3StockType", mIsszmbalv3StockTypeMap);
                bundle.putSerializable("Isszmbalv3SupcustInfo", mIsszmbalv3SupcustInfoSerializableList);
                toIntent.putExtras(bundle);

                View view ;
                if ( (( position == lastExhibitPos[0] ) && !bCanExhibit[0] )   ||  (( position == lastExhibitPos[1] ) && !bCanExhibit[1])) {
                    view = v.findViewById(R.id.stock_secondary_iv);
                }else{
                    view = v.findViewById(R.id.stock_iv);
                }
                forbidExhibitPos = position;
                /**
                 * Now create an {@link android.app.ActivityOptions} instance using the
                 * {@link ActivityOptionsCompat#makeSceneTransitionAnimation(Activity, Pair[])} factory
                 * method.
                 */
                Pair<View, String> pContent = Pair.create(v.findViewById(R.id.stock_name_tv),Isszmbalv3StockEditActivity.VIW_NAME_HEAD_TOOLBAR);
                Pair<View, String> pContent1 = Pair.create(v.findViewById(R.id.stock_rem_tv),Isszmbalv3StockEditActivity.VIEW_NAME_HEADER_TITLE);
                Pair<View, String> pImage = Pair.create(view, Isszmbalv3StockEditActivity.VIEW_NAME_HEADER_IMAGE);
                @SuppressWarnings("unchecked")
                    ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
                            getActivity(),
//                            // Now we provide a list of Pair items which contain the view we can transitioning
//                            // from, and the name of the view it is transitioning to, in the launched activity
                            pImage,pContent,pContent1);
                        //ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        //getActivity(),
                        // Now we provide a list of Pair items which contain the view we can transitioning
                        // from, and the name of the view it is transitioning to, in the launched activity
                     //   pImage);
//                    @SuppressWarnings("unchecked")
//                    ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation(
//                            getActivity(),
//                            // Now we provide a list of Pair items which contain the view we can transitioning
//                            // from, and the name of the view it is transitioning to, in the launched activity
//                            v.findViewById(R.id.icon_rl), Isszmbalv3StockEditActivity.VIEW_NAME_HEADER_IMAGE);
                startActivityForResult(toIntent, ACTIVITY_RESULT_STOCK_DETAIL, activityOptions.toBundle());

                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(-1);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }

            @Override
            public void onItemLongClick(View v, int position) {
                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(position);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(position, "menu");
                } else {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(position);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(position, "menu");
                }
            }

            @Override
            public void onMenuClick(View v, int position) {
                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(position);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(position, "menu");
                } else {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(position);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(position, "menu");
                }
            }

            @Override
            public void onMaskClick(View v, int position) {
                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(-1);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }
        });

        mIsszmbalv3StockRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsszmbalv3StockListGetProcessListener != null) {
                    mIsszmbalv3StockListGetProcessListener.onIsszmbalv3StockListViewTouchEvent(event);
                }
                return false;
            }
        });
        mIsszmbalv3StockRecyclerView.addOnScrollListener(mOnScrollListener);
    }

    private PtrDefaultHandler2 ptrDefaultHandler2 = new PtrDefaultHandler2() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return !mIsTitleLlHided && PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            getIsszmbalv3StockInfoList(true);
        }

        @Override
        public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
            return false && PtrDefaultHandler2.checkContentCanBePulledUp(frame, content, footer);
        }

        @Override
        public void onLoadMoreBegin(PtrFrameLayout frame) {
            mPtrFrame.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPtrFrame.refreshComplete();
                }
            }, 0);
        }
    };

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {
        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if (mCanLoadMore) {
                getIsszmbalv3StockInfoList(false);
            }
        }
    };

    /**
     * @desc 2 个定时器同时动画滚动 item 图片
     * @author taoli
     * @time 2017/8/25 0025
     */
    private boolean bCanExhibit[] = {true, true};
    private int lastExhibitPos[] = {-1, -1};
    private CountDownTimer firstVerticalScrollCountDownTimer;
    private CountDownTimer secondVerticalScrollCountDownTimer;
    private void startAnimateExhibit() {
        if (firstVerticalScrollCountDownTimer == null) {
            firstVerticalScrollCountDownTimer = new CountDownTimer(Long.MAX_VALUE, 4500) {
                @Override
                public void onTick(long millisUntilFinished) {
                    int lastVisibleItemPosition = getRecyclerViewLastVisibleItemPosition(mIsszmbalv3StockRecyclerView);
                    int result = lastVisibleItemPosition - new java.util.Random().nextInt(6);
                    if ( ( result == lastExhibitPos[1] && bCanExhibit[0] ) || ( result == forbidExhibitPos ) ) {
                        return;
                    }
                    if (result >= 0 && result <= lastVisibleItemPosition) {
                        if (bCanExhibit[0]) {
                            bCanExhibit[0] = false;
                            lastExhibitPos[0] = result;
                            mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(lastExhibitPos[0], "exhibit");
                        } else {
                            mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(lastExhibitPos[0], "recovery");
                            bCanExhibit[0] = true;
                            lastExhibitPos[0] = -1;
                        }
                    }
                }

                @Override
                public void onFinish() {

                }
            }.start();
        }
        if (secondVerticalScrollCountDownTimer == null) {
            secondVerticalScrollCountDownTimer = new CountDownTimer(Long.MAX_VALUE, 3500) {
                @Override
                public void onTick(long millisUntilFinished) {
                    int lastVisibleItemPosition = getRecyclerViewLastVisibleItemPosition(mIsszmbalv3StockRecyclerView);
                    int result = lastVisibleItemPosition - new java.util.Random().nextInt(6);
                    if ( ( result == lastExhibitPos[0] && bCanExhibit[1]) || ( result == forbidExhibitPos ) ) {
                        return;
                    }
                    if (result >= 0 && result <= lastVisibleItemPosition) {
                        if (bCanExhibit[1]) {
                            bCanExhibit[1] = false;
                            lastExhibitPos[1] = result;
                            mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(lastExhibitPos[1], "exhibit");
                        } else {
                            mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(lastExhibitPos[1], "recovery");
                            bCanExhibit[1] = true;
                            lastExhibitPos[1] = -1;
                        }
                    }
                }

                @Override
                public void onFinish() {

                }
            }.start();
        }
    }

    /**
     * @desc 获取 RecyclerView 最后一个可见 Item 的 position 索引，以便于计算在屏幕范围内需要随机滚动的 Item 索引
     * @author taoli
     * @time 2017/8/30 0030
     */
    private int getRecyclerViewLastVisibleItemPosition(RecyclerView recyclerView) {
        int lastVisibleItemPosition = 0;
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof LinearLayoutManager) {
            lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
        } else if (layoutManager instanceof GridLayoutManager) {
            lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
            int[] lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];
            staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);
            lastVisibleItemPosition = Utils.findMax(lastPositions);
        }
        return lastVisibleItemPosition;
    }

    /**
     * @desc 设置是否可以下拉刷新
     * @author taoli
     * @time 2017/8/30 0030
     */
    public void setTitleIsHided(boolean is) {
        mIsTitleLlHided = is;
    }

    public void setStyle(int s) {
        ListStyle = s;
        mIsszmbalv3StockRecyclerViewAdapter.setStyle(ListStyle);
        if (s == 1) {
            mIsszmbalv3StockRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        } else if (s == 2) {
            mIsszmbalv3StockRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        }
    }

    public void setIsszmbalv3StockSearchSortMode(int m) {
        SortMode = m;
        if (mPtrFrame != null) {
            getIsszmbalv3StockInfoList(true);
        }
    }

    public void setIsszmbalv3StockListStyle(int s) {
        ListStyle = s;
    }

    public void setPosition(int p) {
        this.mPosition = p;
    }

    public void setIsszmbalv3StockTypeMap(SerializableMap map) {
        this.mIsszmbalv3StockTypeMap = map;
    }

    public void setIsszmbalv3SupcustInfoSerializableList(SerializableList list){
        this.mIsszmbalv3SupcustInfoSerializableList = list;
    }

    private int mDeletePosition = -1;

    public void showDeleteItemDialog(final int positionStock) {
        final Isszmbalv3StockInfo isszmbalv3StockInfo = mIsszmbalv3StockRecyclerViewAdapter.getItem(positionStock);
        DialogUtil.showDeleteItemDialog(getActivity(), isszmbalv3StockInfo.item_name.trim(), new Runnable() {
            @Override
            public void run() {
            }
        }, new Runnable() {
            @Override
            public void run() {
                mDeletePosition = positionStock;
                new DeleteIsszmbalv3StockInfoTask().execute(isszmbalv3StockInfo.item_no);
            }
        });
    }

    private synchronized void getIsszmbalv3StockInfoList(boolean headerOrFooter) {
        if (getActivity() != null && getActivity().isFinishing()) {
            return;
        }
        if (!bCanRefresh)
            return;

        new GetIsszmbalv3StockInfoListTask(headerOrFooter).execute();
    }

    private class GetIsszmbalv3StockInfoListTask extends AsyncTask<Void, Void, List<Isszmbalv3StockInfo>> {
        private boolean mHeaderOrFooter;

        public GetIsszmbalv3StockInfoListTask(boolean headerOrFooter) {
            mHeaderOrFooter = headerOrFooter;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            bCanRefresh = false;
        }

        @Override
        protected List<Isszmbalv3StockInfo> doInBackground(Void... params) {
            if (getActivity() != null && getActivity().isFinishing()) {
                return null;
            }

            List<Isszmbalv3StockInfo> result = null;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                if (mHeaderOrFooter == true) {
                    mStartIndex = 0;
                    // 请求商品最大数量
                    mMaxStockCountByTypeId = DatabaseManager.getIsszmbalv3StockCountFromSqlServer(getActivity(), mStockTypeId);
                    if (mStockTypeId.equals("-1"))
                        mMaxStockIndex = mMaxStockCountByTypeId;
                }
                result = DatabaseManager.getIsszmbalv3StockInfoListFromSqlServer(getActivity(), mStartIndex, BarApplication.pagesize, mMaxStockCountByTypeId, 0, SortMode, mStockTypeId);
            } else {
                if (mHeaderOrFooter == true) {
                    mStartIndex = 0;
                }
                result = DatabaseManager.getIsszmbalv3StockInfoListFromLocal(getActivity(), mStartIndex, BarApplication.pagesize, 0, SortMode, mStockTypeId);
            }
            if (result != null) {
                mStartIndex = mStartIndex + result.size();
            }

            return result;
        }

        @Override
        protected void onPostExecute(final List<Isszmbalv3StockInfo> result) {
            super.onPostExecute(result);
            if (getActivity() != null && getActivity().isFinishing()) {
                return;
            }

            if (result != null) {
                synchronized (mLock) {
                    if (mHeaderOrFooter == true) {
                        mCanLoadMore = true;
                    }

                    if (mStartIndex == 0) {
                        //mIsszmbalv3StockRecyclerView.setVisibility(View.GONE);
                        get_stock_list_fail_iv.setVisibility(View.VISIBLE);
                        get_stock_list_fail_tv.setVisibility(View.VISIBLE);
                        get_stock_list_fail_tv.setText("无商品");
                    } else {
                        //mIsszmbalv3StockRecyclerView.setVisibility(View.VISIBLE);
                        get_stock_list_fail_iv.setVisibility(View.GONE);
                        get_stock_list_fail_tv.setVisibility(View.GONE);
                    }

                    if (mIsszmbalv3StockListGetProcessListener != null) {
                        mIsszmbalv3StockListGetProcessListener.onIsszmbalv3StockIndexProcessFinish(mMaxStockCountByTypeId, mPosition);
                    }

                    if (mStockTypeId.equals("-1") && mIsszmbalv3StockListGetProcessListener != null) {
                        mIsszmbalv3StockListGetProcessListener.onIsszmbalv3StockMaxIndexProcessFinish(mMaxStockIndex);
                    }

                    int count = result.size();
                    if (count < BarApplication.pagesize) {
                        mCanLoadMore = false;
                    }
                    if( count != 0 && mHeaderOrFooter){
                        startAnimateExhibit();
                    }
                    if (mHeaderOrFooter) {
                        Message _Msg = mHandler.obtainMessage(REFRESH_DATA_FINISH, result);
                        mHandler.sendMessage(_Msg);
                    } else if (!mHeaderOrFooter) {
                        Message _Msg = mHandler.obtainMessage(LOAD_DATA_FINISH, result);
                        mHandler.sendMessage(_Msg);
                    }
                }
            }

            bCanRefresh = true;
        }
    }

    private class DeleteIsszmbalv3StockInfoTask extends AsyncTask<String, Void, String> {
        public DeleteIsszmbalv3StockInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            String stockNo = params[0];
            long row = -1;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                row = DatabaseManager.deleteIsszmbalv3StockInfoFromSqlServer(getActivity(), stockNo);
            } else {
                row = DatabaseManager.deleteIsszmbalv3StockInfoFromLocal(getActivity(), stockNo);
            }
            return String.valueOf(row);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result.equals("1")) {
                mIsszmbalv3StockRecyclerViewAdapter.removeData(mDeletePosition);
                mIsszmbalv3StockRecyclerViewAdapter.notifyItemRemoved(mDeletePosition);
            }else{
                showTipsDialog("删除失败，请保存截断中文名后再试");
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_RESULT_STOCK_DETAIL) {
            if (resultCode == RESULT_OK) {
                getIsszmbalv3StockInfoList(true);
            }
            forbidExhibitPos = -1;
        }
    }

    private void showTipsDialog(final String tips){
        DialogUtil.showTipsDialog(getActivity(), tips, new Runnable() {
            @Override
            public void run() {
            }
        });
    }

    private Isszmbalv3StockListGetProcessListener mIsszmbalv3StockListGetProcessListener = null;

    public void setIsszmbalv3StockListGetProcessListener(Isszmbalv3StockListGetProcessListener listener) {
        mIsszmbalv3StockListGetProcessListener = listener;
    }

    public interface Isszmbalv3StockListGetProcessListener {
        public void onIsszmbalv3StockMaxIndexProcessFinish(int maxStockIndex);

        public void onIsszmbalv3StockIndexProcessFinish(int maxStockCountByTypeId, int position);

        public void onIsszmbalv3StockListViewTouchEvent(MotionEvent event);
    }
}
